from django.shortcuts import render, redirect
from AppMonitor import ZabbixApi
from AppMonitor import views as AMOviews
from OpManager import settings
from AppManager import Mysql, Crontab
from DomainManager import views as DMviews


@settings.auth(AuthType="NULL", AuthNum=0)
def index(requests):
    cron_count = 0
    for hostname, hostdata in Crontab.CronDict.items():
        for user, userdata in hostdata.items():
            cron_count += len(userdata["data"])
    error_domain_count = 0
    all_domain_count = 0
    try:
        all_domain_count = len(DMviews.DomainDicts[0]["Data"]["Domain"])
        tmpDomain = DMviews.DomainDicts[0]["Data"]["Domain"]
        if not tmpDomain["DomainStatus"] == 3 and tmpDomain["DomainAuditStatus"] == "SUCCEED":
            error_domain_count += 1
    except Exception as e:
        print("展示域名数异常：", type(e), e)
    context = {
        'host_num': getHostCount(),
        'error_host': len(AMOviews.ZabbixProblems[0]),
        'error_domain': error_domain_count,
        'all_domain': all_domain_count,
        'cron_num': cron_count,
        'ProblmeList': AMOviews.ZabbixProblems[0]
    }
    return render(requests, 'index.html', context)


@settings.auth(AuthType="NULL", AuthNum=0)
def notfound(requests):
    return render(requests, '404.html')


@settings.auth(AuthType="NULL", AuthNum=0)
def InvalidAuthority(requests):
    return render(requests, '403.html')


def getHostCount():
    return len(Mysql.MysqlPool("SELECT * FROM `host`", 99))
